package com.itheima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Category;
import com.itheima.bean.Dish;
import com.itheima.bean.Setmeal;
import com.itheima.common.pageParm;
import com.itheima.dao.DishDao;
import com.itheima.dao.SetmealDao;
import com.itheima.dao.categoryDao;
import com.itheima.dto.DishDto;
import com.itheima.exception.CustomException;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealService;
import com.itheima.service.dishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Transactional
@Service
public class categoryServiceImpl implements CategoryService {

    @Resource
    private categoryDao categoryDao;

    @Resource
    private dishService dishService;

    @Resource
    private SetmealService setmealService;

    @Override
    public int add(Category category) {

        return categoryDao.insert(category);

    }

    @Override
    public IPage<Category> findPage(pageParm pageParm) {

        IPage<Category> p = new Page<>(pageParm.getPage(), pageParm.getPageSize());


        return categoryDao.selectPage(p, null);
    }


    //分类不能直接删除

    @Override
    public int delete(Long id, Integer type) {

        List<DishDto> dishList = dishService.findByCategoryId(id, null);

        List<Setmeal> setmealList = setmealService.findByCategoryId(id,null);

        if (type == 1) {
            if (dishList != null && dishList.size() > 0) {//可以返回-1，然后再controller里面判断结果是不是-1，就告诉前端有关联
                //的菜品数据禁止删除
                //return -1;
                throw new CustomException("该分类下有关联的菜品数据,禁止删除");
            }
        } else {
            if (setmealList != null && setmealList.size() > 0) {
                throw new CustomException("该分类下有关联的套餐数据,禁止删除");
                //return -2;
            }
        }


        return categoryDao.deleteById(id);
    }

    @Override
    public int update(Category category) {

        return categoryDao.updateById(category);
    }


    //通过是否是套餐还是菜品类型找
    @Override
    public List<Category> findByType(Integer type) {

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();

        lqw.eq(type != null, Category::getType, type);

        return categoryDao.selectList(lqw);
    }


    @Override
    public Category findById(long cid) {
        return categoryDao.selectById(cid);
    }
}
